package com.maewa.mp3;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class MP3Extractor {
	public static void main(String[] args) throws Exception {
		File inFile = new File("e:/2012.txt");
		List<String> lines = FileUtils.readLines(inFile);
		
		for(String line : lines) {
			String urlString = line.substring(line.indexOf("http://"), line.indexOf(" "));
			String folderName = line.substring(line.indexOf(" ") + 1);

			File dir = new File("E:/My Documents/My Music/2012/" + folderName);
			FileUtils.forceMkdir(dir);
			
			URL url = new URL(urlString);
			InputStream is = url.openStream();
			String html = IOUtils.toString(is);
			
			int startIndex = 0, endIndex = 0;
			while(true) {
				startIndex = html.indexOf("href=\"", startIndex);
				if(startIndex == -1) break;
				
				endIndex = html.indexOf('"', startIndex + 6);
				
				String fileURLString = html.substring(startIndex + 6, endIndex);
				if(fileURLString.contains(".mp3")) {
					String fileName = html.substring(html.indexOf(">", endIndex) + 1, html.indexOf("<", endIndex));
					fileName = fileName.replaceAll("&#8211; ", "");
					fileName = fileName.replaceAll(" TamilWire.com", "");
					fileName = fileName.replaceAll(" TamilWire.Com", "");
					fileName = fileName.replaceAll("_", " ");
					
					File mp3File = new File(dir, fileName);
					System.out.println("Downloading file " + fileURLString + " to " + mp3File);
					FileUtils.copyURLToFile(new URL(fileURLString), mp3File);
				}
				
				startIndex = endIndex + 1;
			}
		}
	}
}
